import Vue from 'vue'
import jwt from 'jsonwebtoken'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import VueRouter from 'vue-router'

//一次性加载所有
// import Login from '@/views/Login.vue'
// import Control from '@/views/Control.vue'
// import Dashboard from '@/views/Dashboard.vue'
// import Admin from '@/views/Admin.vue'
// import User from '@/views/User.vue'


//懒加载
const Login = () => import('@/views/Login.vue')
const Control = () => import('@/views/Control.vue')
const Dashboard = () => import('@/views/Dashboard.vue')
const Admin = () => import('@/views/Admin.vue')
const Role = () => import('@/views/Role.vue')
const Carousel = () => import('@/views/Carousel.vue')
const Productcate = () => import('@/views/Productcate.vue')
const Product = () => import('@/views/Product.vue')
const User = () => import('@/views/User.vue')

Vue.use(VueRouter)

const router = new VueRouter({
  linkActiveClass: 'active',
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    {
      path: '/control',
      component: Control,
      children: [
        { path: '', redirect: 'dashboard' },
        { path: 'dashboard', component: Dashboard, meta: { requireAuth: true } },
        { path: 'admin', component: Admin, meta: { requireAuth: true } },
        { path: 'role', component: Role, meta: { requireAuth: true } },
        { path: 'carousel', component: Carousel, meta: { requireAuth: true } },
        { path: 'productcate', component: Productcate, meta: { requireAuth: true } },
        { path: 'product', component: Product, meta: { requireAuth: true } },
        { path: 'user', component: User, meta: { requireAuth: true } }
      ]
    }
  ]
})

// 验证路由登录权限
router.beforeEach((to, from, next) => {

  //让loadding走起来...
  NProgress.start()

  const token = localStorage.getItem('Gx-Token') // 得到授权码
  let valid = token
  if (token) {
    try {
      jwt.verify(token, '0513')
    } catch (err) {
      Vue.prototype.$notify.error({ title: '授权令牌错误', message: err })
      valid = false
    }
  }

  if (valid) {
    if (to.path === '/login') next('/control')
  } else {
    if (to.meta.requireAuth) next('/login')
  }

  next()
})

//全局后置守卫结束loadding效果
router.afterEach(() => NProgress.done())

export default router
